﻿using System.Collections.Generic;

namespace Core
{
    public static partial class Utils
    {
        public static class ID
        {
            private static readonly object Lock = new();
            private static readonly Dictionary<int, long> Dict = new();

            // 雪花ID：https://github.com/stulzq/snowflake-net
            //private static ushort m_seed_num;

            //public static long GetSnowId(int root_id)
            //{
            //    long time = Utils.Time.ClientNowSeconds();
            //    return (root_id << 48) + (time << 16) + (++m_seed_num);
            //}

            //public static int GetRootId(long v)
            //{
            //    return (int)(v >> 48);
            //}

            /// <summary>
            /// root_id
            /// 小于1024 && 大于等于0
            /// =0 : 客户端生成的ID
            /// >0 : 服务器下发的ID
            /// </summary>
            /// <param name="root_id"></param>
            /// <returns></returns>
            public static long Get(int root_id = 0)
            {
                lock (Lock)
                {
                    if (root_id < 0 || root_id >= 1 << 10) return 0;

                    if (Dict.ContainsKey(root_id) == false)
                    {
                        Dict.Add(root_id, ((long)root_id) << 53);
                    }

                    Dict[root_id]++;

                    return Dict[root_id];
                }
            }

            //private static long m_instance_id;
            //public static long GetId()
            //{
            //    return m_instance_id++;
            //}
        }
    }
}
